import { login, getRoute, getUserInfo } from "@/api/main/login"
import { Module } from "vuex"
import LocalCache from "@/utils/cache"
import { addRoutes } from "@/utils/dynamic-routes"
import type { IRootState } from "../type"
import type { IloginState } from "./types"
import router from "@/router"

const loginMoudle: Module<IloginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: "",
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    saveToken(state, payload) {
      state.token = payload
    },
    saveUserInfo(state, payload) {
      state.userInfo = payload
    },
    saveUserMenus(state, payload) {
      state.userMenus = payload
      state.userMenus.forEach(menu => {
        const routes = addRoutes(menu)
        routes.forEach(route => {
          router.addRoute("main", route)
        })
      })
    }
  },
  actions: {
    async userLogin({ commit }, payload) {
      const loginResult = await login(payload)
      const token = loginResult.data.token
      const username = loginResult.data.username
      const id = loginResult.data.id
      if (token) {
        LocalCache.setCache("token", token)
        commit("saveToken", token)
      }
      const userInfo = await getUserInfo({ username })
      if (userInfo) {
        LocalCache.setCache("userInfo", userInfo.data)
        commit("saveUserInfo", userInfo.data)
      }
      const userMenus = await getRoute({ id })
      if (userMenus) {
        commit("saveUserMenus", userMenus.data)
        LocalCache.setCache("userMenus", userMenus.data)
      }
      router.push("/main")
    },
    // 刷新后保持菜单同步
    initCache({ commit }) {
      const userInfo = LocalCache.getCache("userInfo")
      const userMenus = LocalCache.getCache("userMenus")
      const token = LocalCache.getCache("token")
      if (userInfo) commit("saveUserInfo", userInfo)
      if (userMenus) commit("saveUserMenus", userMenus)
      if (token) commit("saveToken", token)
    }
  }
}
export default loginMoudle
